import logger from '@common/logger';
import { DELIVERY_TYPE } from '@constants/shop';
import { MARKET_SCOPE_TYPE, MARKET_ACTIVITY_OFFER_TYPE_VALUE } from '@constants/market';
// // 处理购物袋数据为可用数据
// export const dealShopBagListData = (bagData, bagWarehouseData) => {
//     const result = [];
//     const { warehouses, cart_prods } = bagWarehouseData;
//     for (let i = 0; i < (warehouses || []).length; i++) {
//         const { is_matched } = warehouses[i];
//         const _list = bagData.filter(item => is_matched ? item.store_id === 0 : item.store_id === warehouses[i].id);
//         _list.length > 0 && result.push({
//             warehouseInfo: warehouses[i],
//             list: _list.map(temp => {
//                 const _item = cart_prods.filter(c => c.prod_id === temp.prod_id)[0];
//                 return {
//                     ...temp,
//                     isSelect: false,
//                     maxQuantity: _item.quantity === -1 ? 999999 : _item.quantity,
//                     isBrandMode: temp.store_id === 0,
//                 };
//             }),
//         });
//     }
//     return result;
// };

export const dealBagListData = (cartList = []) => {
    const storeList = [];
    for (let i = 0; i < cartList.length; i++) {
        const item = cartList[i];
        if (storeList.filter(temp => temp.id === item.store_id).length > 0) continue;
        storeList.push({
            id: item.store_id,
            name: item.store_name,
        });
    }
    return storeList.map(item => {
        return {
            ...item,
            prodsList: [{
                discountInfo: null,
                list: cartList.filter(t => t.store_id === item.id),
            }]
        };
    });
};

// 计算购物车商品数量
export const calcBagProduceLength = (bagList = []) => {
    let len = 0;
    bagList.forEach(item => {
        item.prodsList.forEach(temp => {
            temp.list.forEach(tt => {
                len += tt.quantity;
            });
        });
    });
    return len;
};

// 判断是否全部选中
export const isSelectAll = (bagList=[]) => {
    if (bagList.length === 0) return false;
    logger.debugger('----', bagList);
    let result = [];
    let len = 0;
    for (let i = 0; i < bagList.length; i++) {
        for (let j = 0; j < bagList[i].prodsList.length; j++) {
            len += bagList[i].prodsList[j].list.length;
            for (let t = 0; t < bagList[i].prodsList[j].list.length; t++) {
                const item = bagList[i].prodsList[j].list[t];
                item.isSelect && result.push(1);
            }
        }
    }
    return result.length === len;
};

export const isStoreSelectAll = (storeProdsList) => {
    let result = [];
    let len = 0;
    for (let i = 0; i < storeProdsList.length; i++) {
        len += storeProdsList[i].list.length;
        for (let j = 0; j < storeProdsList[i].list.length; j++) {
            const item = storeProdsList[i].list[j];
            item.isSelect && result.push(1);
        }
    }
    return result.length === len;
};

// 修改整个购物车的全选状态
export const toggleBagSelectStatus = (bagList = []) => {
    const result = [];
    const isAll = isSelectAll(bagList);
    for (let i = 0; i < bagList.length; i++) {
        const itemProdsList = bagList[i].prodsList;
        const _itemProdsList = [];
        for (let j = 0; j < itemProdsList.length; j++) {
            const list = itemProdsList[j].list;
            const _list = [];
            for (let t = 0; t < list.length; t++) {
                const item = list[t];
                _list.push({
                    ...item,
                    isSelect: isAll ? false : true,
                });
            }
            _itemProdsList.push({
                ...itemProdsList[j],
                list: _list,
            });
        }
        result.push({
            ...bagList[i],
            prodsList: _itemProdsList,
        });
    }
    return result;
};

// 修改store分组的选择状态
export const toggleSelectStaus = (list) => {
    const flag = isStoreSelectAll(list);
    return list.map(item => {
        return {
            ...item,
            list: item.list.map(temp => {
                return {
                    ...temp,
                    isSelect: !flag,
                };
            }),
        };
    });
};

// 修改单项选择状态
export const toggleItemSelectStatus = (list, index) => {
    const arr = [ ...list ];
    arr[index].isSelect = !arr[index].isSelect;
    return arr;
};

/**
 * 取消其他分组的选中
 * @param {Array} list 数组
 * @param {Number} index 索引
 */
export const toggleOtherStoreStatus = (list, index) => {
    const arr = [ ...list ];
    return arr.map((item, idx) => {
        return {
            ...item,
            prodsList: idx === index ? item.prodsList : item.prodsList.map(temp => {
                return {
                    ...temp,
                    list: temp.list.map(tt => {
                        return {
                            ...tt,
                            isSelect: false,
                        };
                    }),
                };
            }),
        };
    });
};

// 获取选中的数据
export const getBagSelectItems = (bagList) => {
    logger.debugger(bagList);
    let result = [];
    for (let i = 0; i < bagList.length; i++) {
        for (let j = 0; j < bagList[i].prodsList.length; j++) {
            for (let t = 0; t < bagList[i].prodsList[j].list.length; t++) {
                const item = bagList[i].prodsList[j].list[t];
                item.isSelect && result.push(item);
            }
        }
    }
    return result;
};

// 计算购物袋选中项的总价
export const calcBagTotalPrice = (bagList) => {
    const arr = getBagSelectItems(bagList);
    let totalPrice = 0;
    for (let i = 0; i < arr.length; i++) {
        totalPrice += arr[i].price * arr[i].quantity;
    }
    return totalPrice.toFixed(2);
};

// 获取存在选择的数组信息
export const getSelectStoreListData = (bagList=[]) => {
    const result = [];
    for (let i = 0; i < bagList.length; i++) {
        const storeItem = bagList[i];
        let _prodsList = [];
        for (let j = 0; j < storeItem.prodsList.length; j++) {
            const prodItem = storeItem.prodsList[j];
            let _list = [];
            for (let t = 0; t < prodItem.list.length; t++) {
                const item = prodItem.list[t];
                if (item.isSelect) {
                    _list.push(item);
                }
            }
            if (_list.length > 0) {
                _prodsList.push({
                    ...prodItem,
                    list: _list,
                });
            }
        }
        if (_prodsList.length > 0) {
            result.push({
                ...storeItem,
                prodsList: _prodsList,
            });
        }
    }
    return result;
};

/**
 * 获取选中的商品
 * @param {Array}} bagList 购物袋数据
 */
export const getSelectProductList = (bagList) => {
    return getBagSelectItems(bagList);
};

// 购物袋数据转换成预览数据
export const bagDataToReviewData = (selectList) => {
    const result = [];
    for (let i = 0; i < selectList.length; i++) {
        const storeItem = selectList[i];
        let _list = [];
        storeItem.prodsList.forEach(item => {
            _list =  _list.concat(item.list);
        });
        result.push({
            id: storeItem.id,
            name: storeItem.name,
            list: _list,
            couponList: [],
            useCoupon: [],
            discountInfo: {},
            remark: '',
            warehouseInfo: {
                city_regions: [{ start_fee: 0, express_fee: 0 }],
                ordinary_express_config: { first: 0, additional: 0 },
            },
            deliveryPrice: 0,
            totalPrice: 0,
            totalDiscountPrice: 0,
        });
    }
    return result;
};

const dealOrderItemWarehouseInfo = (info) => {
    const isCity = info.city_express && info.city_regions && info.city_regions.length > 0;
    const deliveryType = info.ordinary_express ? DELIVERY_TYPE.EXPRESS : (isCity ? DELIVERY_TYPE.CITY_EXPRESS : (info.pick_up ? DELIVERY_TYPE.SELF_PICK_UP : DELIVERY_TYPE.EXPRESS));
    return {
        warehouseName: info.name,
        warehouseId: info.warehouse_id,
        isCity: info.city_express, // 是否支持同城
        isCityBeyond: info.city_express && info.city_regions && info.city_regions.length === 0, // 是否是超出配送范围
        isExpress: info.ordinary_express, // 是否支持快递
        isPickUp: info.pick_up, // 是否支持自提
        deliveryType, // 配送方式
        timeDays: 0, // 自提、当日达时间
    };
};

const getProductListActivity = (list, activityList) => {
    const prodsIds = list.map(item => item.prod_id);
    const result = {};
    for (let i = 0; i < activityList.length; i++) {
        const { scope, item_confs, offer_type } = activityList[i];
        switch(scope) {
        case MARKET_SCOPE_TYPE.unlimited:

            break;
        case MARKET_SCOPE_TYPE.includeItems:
            break;
        case MARKET_SCOPE_TYPE.excludeItems:
            break;
        }
    }
};

const bagItemAddDiscount = (storeItem, activityInfo) => {
    const { name, id, prodsList } = storeItem;
    let allProds = [];
    prodsList.map(item => {
        allProds = [...allProds, ...item.list];
    });

    let _prodsList = [];
    let useIds = [];
    activityInfo.offer_items.map(temp => {
        const { off_trial_items, offer_item_trial_info, offer_type } = temp;
        let _discountInfo = {
            tag: MARKET_ACTIVITY_OFFER_TYPE_VALUE[offer_type],
            value: offer_item_trial_info.name,
        };
        _prodsList.push({
            discountInfo: _discountInfo,
            list: off_trial_items.map(tt => {
                useIds.push(`${tt.item_id}_${tt.item_spec_id}`);
                return allProds.filter(kk => kk.prod_id == tt.item_id && kk.sku_id == tt.item_spec_id)[0];
            }),
        });
    });
    _prodsList.push({
        discountInfo: null,
        list: allProds.filter(item => useIds.indexOf(`${item.prod_id}_${item.sku_id}`) == -1),
    });
    logger.info('Bag => 单项添加优惠', _prodsList);
    return {
        id,
        name,
        prodsList: _prodsList,
    };
};

/**
 * 购物车添加活动信息
 * @param {Array} bagList 购物车数据
 * @param {Array} activityList 活动信息
 */
export const dealBagAddActivity = (bagList, activityList) => {
    if (activityList.length === 0) return bagList;
    let result = [];
    for (let i = 0; i < bagList.length; i++) {
        logger.warn('Bag => 单项', bagList[i]);
        result.push(bagItemAddDiscount(bagList[i], activityList[i]));
    }
    return result;
};
